import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'

// 导入ECharts
import ECharts from 'vue-echarts'
import { use } from 'echarts/core'

// 手动引入 ECharts 各模块来减小打包体积
import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  LineChart,
  BarChart,
  PieChart
} from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  DataZoomComponent
])

// 引入Element Plus配置
import { setupElementPlus } from '@/plugins/element-plus'

// 引入全局样式
import '@/styles/variables.css'
import '@/styles/global.css'
import '@/styles/components.css'

// 处理 ResizeObserver 错误
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const _ResizeObserver = window.ResizeObserver
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
  constructor(callback) {
    callback = debounce(callback, 20)
    super(callback)
  }
}

// 全局错误处理
window.addEventListener('error', (e) => {
  if (e.message === 'ResizeObserver loop completed with undelivered notifications.') {
    const resizeObserverErrDiv = document.getElementById('webpack-dev-server-client-overlay-div')
    const resizeObserverErr = document.getElementById('webpack-dev-server-client-overlay')
    if (resizeObserverErr) {
      resizeObserverErr.setAttribute('style', 'display: none')
    }
    if (resizeObserverErrDiv) {
      resizeObserverErrDiv.setAttribute('style', 'display: none')
    }
  }
  
  // 处理Element Plus getComputedStyle错误
  if (e.message.includes('getComputedStyle') || 
      e.message.includes('parameter 1 is not of type') ||
      e.message.includes('resetSelectionWidth')) {
    console.warn('Element Plus DOM access warning (ignored):', e.message)
    e.preventDefault()
    return false
  }
})

// 处理未捕获的Promise错误
window.addEventListener('unhandledrejection', (e) => {
  if (e.reason && e.reason.message && (
    e.reason.message.includes('getComputedStyle') ||
    e.reason.message.includes('parameter 1 is not of type') ||
    e.reason.message.includes('resetSelectionWidth')
  )) {
    console.warn('Element Plus Promise warning (ignored):', e.reason.message)
    e.preventDefault()
    return false
  }
})

// 等待DOM完全加载后再初始化应用
const initializeApp = () => {
  try {
    // 创建Vue应用
    const app = createApp(App)

    // 添加全局错误处理
    app.config.errorHandler = (err, vm, info) => {
      // 忽略Element Plus的DOM访问错误
      if (err.message && (
        err.message.includes('getComputedStyle') ||
        err.message.includes('parameter 1 is not of type') ||
        err.message.includes('resetSelectionWidth')
      )) {
        console.warn('Element Plus DOM access warning (ignored):', err.message)
        return
      }
      console.error('Vue error:', err, info)
    }

    // 使用插件
    app.use(store)
    app.use(router)
    
    // 使用优化的Element Plus配置
    setupElementPlus(app)

    // 注册ECharts组件
    app.component('v-chart', ECharts)

    // 导入认证工具
    const { handlePageRefresh } = require('@/utils/auth')

    // 处理页面刷新时的状态恢复
    handlePageRefresh().then((result) => {
      if (result.success) {
        console.log('页面刷新状态恢复成功:', result.message)
      } else {
        console.log('页面刷新状态恢复失败:', result.message)
      }
    }).catch((error) => {
      console.error('页面刷新状态恢复出错:', error)
    })

    // 挂载应用
    app.mount('#app')
    
    // 应用初始化成功
  } catch (error) {
    console.error('应用初始化失败:', error)
  }
}

// 确保DOM完全加载后再初始化
const waitForDOM = () => {
  return new Promise((resolve) => {
    if (document.readyState === 'complete') {
      resolve()
    } else if (document.readyState === 'interactive') {
      // DOM已加载但资源可能还在加载
      setTimeout(resolve, 50)
    } else {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(resolve, 50)
      })
    }
  })
}

// 等待DOM准备好后初始化应用
waitForDOM().then(() => {
  // 再次确保页面完全准备好
  requestAnimationFrame(() => {
    initializeApp()
  })
})
